import {
  attachmentList,
  attachmentTypes,
  attachmentCategory
} from "@/api/general";

import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted } from "vue";

import { getFilter } from "@/utils/filter";

export function useScript(tableRef: Ref, FormInline: Ref) {
  const form = reactive({
    category: "",
    mimetype: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const categorys = ref([]);
  const mimetypes = ref([]);

  const imagetype = ["jpg", "png", "PNG", "JPG", "jpeg", "JPEG", "gif", "GIF"];

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "类型",
      prop: "category",
      minWidth: 100
    },
    {
      label: "预览",
      prop: "url",
      width: 100,
      cellRenderer: ({ row }) =>
        // 如果再imagetype数组中，则显示图片，否则显示类型
        // 如果时视频文件，显示视频图标
        // 其他文件显示文件图标

        imagetype.includes(row.imagetype) ? (
          <el-image
            preview-teleported
            loading="lazy"
            src={row.url}
            initial-index={row.id}
            fit="cover"
            class="w-[100px] h-[100px]"
          />
        ) : (
          <video controls type="video/mp4" src={row.url} fit="cover" />
        )
    },
    {
      label: "文件大小(kb)",
      prop: "filesize",
      minWidth: 100
    },
    {
      label: "宽度(px)",
      prop: "imagewidth",
      minWidth: 100
    },
    {
      label: "高度(px)",
      prop: "imageheight",
      minWidth: 100
    },
    {
      label: "类型",
      prop: "imagetype",
      minWidth: 100
    },
    {
      label: "存储引擎",
      prop: "storage",
      minWidth: 100
    },
    // 操作列，增加选择按钮
    {
      label: "操作",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-button
          size="mini"
          type="danger"
          onClick={() => {
            setCurrent(row);
          }}
        >
          选择
        </el-button>
      )
    }
  ];

  // 如果FormInline.value.status==true,不显示操作部分
  // 乳沟FormInline.value.status==false,不限显示label
  if (FormInline.value.status) {
    columns[columns.length - 1]["hide"] = true;
  } else {
    columns[0]["hide"] = true;
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = parseInt(val as any);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    FormInline.value.fileList = val;
    console.log(val);
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    if (FormInline.value.status) {
      selectedNum.value = val.length;
      FormInline.value.fileList = val;
    }
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  const setCurrent = (row?: any) => {
    // 获取表格的方法 tableRef.value.getTableRef()
    const { setCurrentRow } = tableRef.value.getTableRef();
    setCurrentRow(row);
    FormInline.value.fileList = row;
  };

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  async function onSearch() {
    loading.value = true;

    let filter = await getFilter(form);

    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "desc"
    };

    const { data } = await attachmentList(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
    attachmentCategory().then(res => {
      categorys.value = [];
      categorys.value.unshift("默认分类");
      categorys.value = categorys.value.concat(res.data);
    });
    // 获取附件类型
    // mimetype
    attachmentTypes().then(res => {
      mimetypes.value = [];
      mimetypes.value = mimetypes.value.concat(res.data);
    });
  });

  return {
    form,
    loading,
    columns,
    dataList,
    mimetypes,
    imagetype,
    categorys,
    pagination,
    selectedNum,
    onSearch,
    resetForm,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
